import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import FileComponent from "./files/FileComponent.js";
import GeneralView from "./GeneralView.js";
import CommonView from "./CommonView.js";
import NotesBlockView from './NotesBlockView.js';
import PaymentConditionBlockView from './payments/PaymentConditionBlockView.js';
import PaymentBlockView from './payments/PaymentBlockView.js';
import DisplayOptionsView from "./DisplayOptionsView";

import StatusView from 'common/views/StatusView.js';
import RelatedEstimationCollectionView from "./related_estimation/RelatedEstimationCollectionView";
import LoginView from 'base/views/LoginView.js';
import ErrorView from 'base/views/ErrorView.js';
import {
    showLoader,
    hideLoader
} from '../../tools.js';
import showCompositionComponent from "./composition";
import ResumeView from './resume/ResumeView.js';
import PDFViewerPopupView from "../../common/views/PDFViewerPopupView";
import NodeFileViewerPopupView
from "../../common/views/NodeFileViewerPopupView";


const template = require('./templates/RootComponent.mustache');

/**
 * Root Component showing all the app blocks
 * 
 * NB : action toolbar is handled separately because for now the status of the 
 * document is computed server-side
 * 
 * Ideally we should have all under this component
 */
const RootComponent = Mn.View.extend({
    template: template,
    regions: {
        modalRegion: '#modalregion',
        resumeRegion: "#resumeregion",
        actions_toolbar: {
            el: "#actions_toolbar",
            replaceElement: true
        },
        errors: '#main-error-region',

        related_estimation: '.related-estimation',

        general: '.general-informations',
        files: "#files",
        common: '.common-informations',
        display_options: '.display-options',
        composition: '.composition',
        notes: '.notes',
        payment_conditions: '.payment-conditions',
        payments: '.payments',

    },
    initialize: function (options) {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        // This event is fired by the ActionToolBar on the Facade and we connect 
        // here to show the StatusView (modal)
        this.listenTo(this.facade, 'status:change', this.onStatusChange);
        this.listenTo(this.facade, 'show:preview', this.onShowPreview);
    },
    showStatusView(action) {
        /*
            Modale de changement de statut
        */
        var model = this.facade.request('get:model', 'common');
        var view = new StatusView({
            action: action,
            model: model
        });
        this.showChildView('modalRegion', view);
    },
    /**
     * Vue résumé (Affiche les Totaux)
     */
    showResumeView() {
        var model = this.facade.request('get:model', 'total');
        const view = new ResumeView({
            model: model
        });
        this.showChildView("resumeRegion", view);
    },
    showEstimationLinked: function () {
        /*
            Lien vers les devis liés (pour les factures)
        */
        var collection = this.facade.request('get:collection', 'related_estimations');
        if (collection && collection.length > 0) {
            var view = new RelatedEstimationCollectionView({
                collection: collection
            });
            this.showChildView('related_estimation', view);
        }
    },
    showGeneralBlock: function () {
        var section = this.config.request('get:form_section', 'general');
        var model = this.facade.request('get:model', 'general');
        var view = new GeneralView({
            model: model,
            section: section
        });
        this.showChildView('general', view);
    },
    showFileBlock: function () {
        var section = this.config.request(
            'get:form_section', 'files'
        );

        var view = new FileComponent({
            section: section
        });
        this.showChildView('files', view);
    },
    showCommonBlock: function () {
        var section = this.config.request('get:form_section', 'common');
        var model = this.facade.request('get:model', 'common');
        var view = new CommonView({
            model: model,
            section: section
        });
        this.showChildView('common', view);
    },
    showDisplayOptions() {
        const section = this.config.request('get:form_section', 'display_options');
        const model = this.facade.request('get:model', 'display_options');
        const view = new DisplayOptionsView({
            model: model,
            section: section,
        });
        this.showChildView('display_options', view);
    },
    showCompositionBlock() {
        const totalmodel = this.facade.request('get:model', 'total');
        const section = this.config.request('get:form_section', 'composition');
        const region = this.getRegion("composition");
        showCompositionComponent(region, section, totalmodel)

    },
    showNotesBlock: function () {
        var section = this.config.request('get:form_section', 'notes');
        var model = this.facade.request('get:model', 'notes');
        var view = new NotesBlockView({
            model: model,
            section: section
        });
        this.showChildView('notes', view);
    },
    showPaymentConditionsBlock: function () {
        var section = this.config.request('get:form_section', 'payment_conditions');
        var model = this.facade.request('get:model', 'payment_conditions');
        var view = new PaymentConditionBlockView({
            model: model
        });
        this.showChildView('payment_conditions', view);
    },
    showPaymentBlock: function () {
        var section = this.config.request('get:form_section', 'payments');
        var model = this.facade.request('get:model', 'payment_options');
        var collection = this.facade.request('get:collection', 'payment_lines');
        var view = new PaymentBlockView({
            model: model,
            collection: collection,
            section: section
        });
        this.showChildView('payments', view);
    },
    showLogin: function () {
        var view = new LoginView({});
        this.showChildView('modalRegion', view);
    },

    onRender: function () {
        this.showResumeView();

        this.showEstimationLinked();
        if (this.config.request('has:form_section', 'files')) {
            this.showFileBlock();
        }
        if (this.config.request('has:form_section', 'general')) {
            this.showGeneralBlock();
        }
        if (this.config.request('has:form_section', 'common')) {
            this.showCommonBlock();
        }
        if (this.config.request('has:form_section', 'display_options')) {
            this.showDisplayOptions();
        }
        if (this.config.request('has:form_section', 'composition')) {
            this.showCompositionBlock();
        }
        if (this.config.request('has:form_section', "notes")) {
            this.showNotesBlock();
        }
        if (this.config.request('has:form_section', "payment_conditions")) {
            this.showPaymentConditionsBlock();
        }
        if (this.config.request('has:form_section', "payments")) {
            this.showPaymentBlock();
        }

    },
    formOk() {
        var result = true;
        var errors = this.facade.request('is:valid');
        if (!_.isEmpty(errors)) {
            this.showChildView(
                'errors',
                new ErrorView({
                    errors: errors
                })
            );
            result = false;
        } else {
            this.detachChildView('errors');
        }
        return result;
    },
    onShowPreview(target, popupTitle, documentTitle) {
        if (target instanceof Object) {
            this.onShowPreviewNodeFileModel(target, popupTitle);
        } else {
            this.onShowPreviewPdfUrl(target, popupTitle, documentTitle);
        }
    },
    onShowPreviewPdfUrl(url, popupTitle, documentTitle) {
        if (url === undefined) {
            url = window.location.pathname + ".pdf";
        }
        if (popupTitle === undefined) {
            popupTitle = "Prévisualisation";
        }
        if (documentTitle === undefined) {
            documentTitle = "";
        }
        let view = new PDFViewerPopupView({
            pdfUrl: url,
            popupTitle: popupTitle,
            documentTitle: documentTitle,
        })
        this.showChildView('modalRegion', view);
    },
    /**
     *
     * @param {NodeFileModel} file
     * @param {String} popupTitle optional popup title (defaults to file name)
     */
    onShowPreviewNodeFileModel(file, popupTitle) {
        let view = new NodeFileViewerPopupView({
            file: file,
            popupTitle: popupTitle,
        });
        this.showChildView('modalRegion', view);
    },
    onStatusChange: function (model) {
        if (!model.get('status')) {
            return;
        }
        showLoader();

        if (model.get('status') != 'draft') {
            console.log("Status is not draft, validating all data");
            if (!this.formOk()) {
                document.getElementById('target_content').scrollTop = document.documentElement.scrollTop = 0;
                hideLoader();
                return;
            }
        }
        const deferred = this.facade.request('save:all');
        deferred.then(
            () => {
                hideLoader();
                this.showStatusView(model)
            },
            () => {
                hideLoader();
            }
        )
    },
    onChildviewDestroyModal: function () {
        this.getRegion('modalRegion').empty();
    }
});
export default RootComponent;